

import allure
from time import sleep
import re

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.ui import WebDriverWait
from common.logger import log

@allure.step("鼠标左键点击")
def sel_left_click(driver, sel,note = '', timeout=10,):
    """
    driver为浏览器驱动实例
    sel为元素定位
    note为备注，用于日志排查，默认为空
    timeout为显示等待时间，默认10s
    Selenium 左键点击操作
    """
    try:
        WebDriverWait(driver, timeout).until(expected_conditions.element_to_be_clickable(sel)).click()
        sleep(0.2)
        # 正则表达式修复，移除中文字符
        selen = re.sub('[\u4e00-\u9fa5]', '', str(sel))
        if len(selen) > 0:
            log.debug(f"点击,{selen}------{note}")
        return True
    except Exception as e:
        log.error(f"无法定位到元素{sel}, 异常为 {e}")
        raise e

@allure.step("输入内容")
def sel_send_keys(driver, sel, value,note = '', timeout=10):
    """
    driver为浏览器驱动实例
    sel为元素定位
    value为输入值
    note为备注，用于日志排查，默认为空
    timeout为显示等待时间，默认10s
    Selenium 左键点击操作
    """
    try:
        WebDriverWait(driver, timeout).until(expected_conditions.element_to_be_clickable(sel)).clear()
        sleep(0.2)
        WebDriverWait(driver, timeout).until(expected_conditions.element_to_be_clickable(sel)).send_keys(value)
        sleep(0.2)
        # 正则表达式修复，移除中文字符
        selen = re.sub('[\u4e00-\u9fa5]', '', str(sel))
        if len(selen) > 0:
            log.debug(f"点击,{selen}，并输入{value}-------{note}")  # 修改为正确的变量名称 selen
        return True
    except Exception as e:
        log.error(f"无法定位元素，{sel}, 异常为 {e}")
        raise e

@allure.step("获取文本内容")
def get_text(driver, sel, note = "",timeout=10, mode=0):
    """
    driver为浏览器驱动实例
    sel为元素定位
    note为备注，用于日志排查，默认为空
    timeout为显示等待时间，默认10s
    Selenium 左键点击操作
    """
    try:
        element = WebDriverWait(driver, timeout).until(expected_conditions.presence_of_element_located(sel))
        if mode == 0:
            log.debug(element.text,f"-------{note}")
            return element.text
        elif mode == 1:
            log.debug(element.get_attribute('textContent'),f"-------{note}")
            return element.get_attribute('textContent')
    except Exception as e:
        log.error(f"文本提取错误，{e}")
        return None



























